//
//  MineCollectionViewController.m
//  HAHAWENWAN
//
//  Created by 李小龙 on 2017/9/20.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "MineCollectionViewController.h"
#import "TitleSelectionView.h"
//#import "MineCollectionShopTableViewCell.h"
//#import "MineCollectionGoodsTableViewCell.h"
//#import "MineCollectionGoodsModel.h"
//#import "MineCollectionShopModel.h"
#import "GoodsDetailViewController.h"
#import "GoodsListCommonCell.h"
#import "GoodsListModel.h"

@interface MineCollectionViewController ()<UITableViewDataSource, UITableViewDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (nonatomic, strong) UITableView *leftTableView;
@property (nonatomic, strong) NSMutableArray *leftDataArr;

@property (nonatomic, assign) NSInteger leftCurrentPage;
@property (nonatomic, assign) NSInteger leftTotalPage;

@end

@implementation MineCollectionViewController
static NSString *goodsTableViewIdentifier = @"MineCollectionGoodsTableIdentifier";
#pragma mark - UIViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configureUI];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self loadLeftNewData];
    
    [self settingTableViewAdjustment:self.leftTableView];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.leftTableView.frame = CGRectMake(0, 0, self.view.width, self.view.height);
}
#pragma mark - action
- (void)configureUI {
    self.view.backgroundColor = [UIColor backgroundColor];
    
    [self.leftTableView registerNib:[UINib nibWithNibName:@"GoodsListCommonCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:goodsTableViewIdentifier];
    [self.leftTableView clearExtendCellLine];
    [self.view addSubview:self.leftTableView];
    
    self.title = @"我的收藏";
    
    __weak typeof(self) weakSelf = self;
    self.leftCurrentPage = 1;
    self.leftTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.leftCurrentPage = 1;
        [weakSelf loadLeftNewData];
    }];
    self.leftTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.leftCurrentPage += 1;
        [weakSelf loadLeftNewData];
    }];
    
    [self.leftTableView.mj_footer setHidden:YES];
}
#pragma mark - 网络请求
- (void)loadLeftNewData {
    // 我收藏的商品列表
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:PageSize forKey:@"pageSize"];
    [parameters safeSetObject:@(self.leftCurrentPage) forKey:@"pageNumber"];
    __weak typeof(self) weakSelf = self;
    
    [MYAFNetworking POST:URL_Get_Collection parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [weakSelf.leftTableView setHidden:NO];
        [weakSelf.leftTableView.mj_header endRefreshing];
        [weakSelf.leftTableView.mj_footer endRefreshing];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSDictionary *data = [responseDic safeJsonObjectForKey:@"data"];
            weakSelf.leftCurrentPage = [[data safeObjectForKey:@"pageNumber"] integerValue];
            weakSelf.leftTotalPage = [[data safeObjectForKey:@"totalPage"] integerValue];
            
            if (weakSelf.leftCurrentPage == 1) {
                [weakSelf.leftDataArr removeAllObjects];
                [weakSelf.leftTableView.mj_footer resetNoMoreData];
            }
            if (weakSelf.leftCurrentPage == weakSelf.leftTotalPage) {
                [weakSelf.leftTableView.mj_footer endRefreshingWithNoMoreData];
            }
            NSArray *list = [data safeJsonObjectForKey:@"list"];
            if (list.count == [data[@"totalRow"] intValue]) {
                [weakSelf.leftTableView.mj_footer setHidden:YES];
            } else {
                [weakSelf.leftTableView.mj_footer setHidden:NO];
            }
            for (NSDictionary *modelDic in list) {
                GoodsListModel *model = [GoodsListModel mj_objectWithKeyValues:modelDic];
                [weakSelf.leftDataArr addObject:model];
            }
            [weakSelf.leftTableView reloadData];
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:code animated:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
        [weakSelf.leftTableView.mj_header endRefreshing];
        [weakSelf.leftTableView.mj_footer endRefreshing];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [weakSelf.leftTableView setHidden:NO];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.leftDataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GoodsListCommonCell *goodsCell = [tableView dequeueReusableCellWithIdentifier:goodsTableViewIdentifier forIndexPath:indexPath];
    GoodsListModel *model = [self.leftDataArr objectAtIndex:indexPath.row];
    [goodsCell setValueForCellWithModel:model];
    
    return goodsCell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 点击跳转商品详情页
    GoodsListModel *model = self.leftDataArr[indexPath.row];
    if (!model.isshelves) {
        [MBProgressHUD showError:self.view title:@"该商品已下架" code:@"" animated:YES];
        return;
    }
    GoodsDetailViewController *goodDetailVC = [[GoodsDetailViewController alloc] init];
    goodDetailVC.gid = model.gid;
    [self.navigationController pushViewController:goodDetailVC animated:YES];
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [GoodsListCommonCell getHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    [view setBackgroundColor:[UIColor backgroundColor]];
    return view;
}

#pragma mark - 左滑删除
// 左滑删除
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

//左滑点击事件
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {  //删除事件
        
    }
}

-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    UITableViewRowAction *button = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        [self showAlertWithTitleArray:@[@"取消",@"确认"] title:@"温馨提示" message:@"确认从收藏列表中移除该商品吗？" alertStyle:UIAlertControllerStyleAlert];
        self.alertBlock = ^(NSString *actionTitle) {
            if ([actionTitle isEqualToString:@"确认"]) {
                GoodsListModel *model = [weakSelf.leftDataArr safeObjectAtIndex:indexPath.row];
                [weakSelf deleteGoodsItem:model indexPath:indexPath];
            }
        };
        NSLog(@"Action to perform with Button 1");
    }];
    //    button.backgroundColor = [UIColor ThemeColor]; //arbitrary color
    return @[button];
}
- (void)deleteGoodsItem:(GoodsListModel *)model indexPath:(NSIndexPath *)indexPath {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    [parameters safeSetObject:model.gid forKey:@"gid"];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Cancel_Collect parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            
            [weakSelf.leftDataArr removeObjectAtIndex:indexPath.row];
            
            // 适配iOS11
            if (@available(iOS 11.0, *)) {
                [weakSelf.leftTableView performBatchUpdates:^{
                    [weakSelf.leftTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                } completion:^(BOOL finished) {
                    [weakSelf.leftTableView reloadData];
                }];
            } else {
                [weakSelf.leftTableView beginUpdates];
                [weakSelf.leftTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                [weakSelf.leftTableView endUpdates];
            }
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:nil animated:YES];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }];
}

#pragma mark - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    return [[NSAttributedString alloc] initWithString:@"暂无收藏商品"
                                           attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                        NSForegroundColorAttributeName:[UIColor grayTextColor]}];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    [self.leftTableView setHidden:YES];
    [self loadLeftNewData];
}
#pragma mark - Getters
- (UITableView *)leftTableView {
    if (!_leftTableView) {
        _leftTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _leftTableView.dataSource = self;
        _leftTableView.delegate = self;
        _leftTableView.backgroundColor = [UIColor backgroundColor];
        [_leftTableView setSeparatorColor:[UIColor colorWithHex:0xE5E5E5 alpha:1.0]];
        [_leftTableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
        _leftTableView.emptyDataSetSource = self;
        _leftTableView.emptyDataSetDelegate = self;
    }
    return _leftTableView;
}

- (NSMutableArray *)leftDataArr {
    if (!_leftDataArr) {
        _leftDataArr = [[NSMutableArray alloc] init];
    }
    return _leftDataArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
